package com.cpit.qualitycontrol.web.controller;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.dto.LogModule;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.service.OperLogService;
import com.cpit.qualitycontrol.common.constant.LogConstantEx;
import com.cpit.qualitycontrol.entity.ProcessRule;
import com.cpit.qualitycontrol.service.ProcessRuleService;
import com.cpit.qualitycontrol.service.impl.ServiceUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Date;

/**
 * Created by Hull on 2017/9/30.
 * @author Hull
 * 流程规则Controller类
 */
@RestController
@RequestMapping(value = "/ProcessRule")
public class ProcessRuleController {
    private String logModule = "流程规则：";
    private final String loggerName = this.getClass().getName();

    @Autowired
    private ProcessRuleService processRuleService = null;

    @Autowired
    private OperLogService operLogService;

    @ApiOperation(value="查询所有流程规则", notes="无条件查询流程规则信息，返回对象List")
    @ResponseBody
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value="/queryAllProcessRule", method = RequestMethod.GET)
    public List<ProcessRule> queryAllProcessRule() {
        return this.processRuleService.findAll();
    }

    @ApiOperation(value="创建流程规则", notes="用户手工指定流程规则并创建，" +
            "需要手动输入流程规则名称和描述信息，流程规则名称不能重复。")
    @ApiImplicitParam(name = "data", value = "流程规则对象", required = true, dataType = "ProcessRule")
    //@PreAuthorize("hasAuthority('createProcessRule')")
    @RequestMapping(value="/createProcessRule", method = RequestMethod.POST)
    public Result<ProcessRule> createProcessRule(@RequestBody ProcessRule data) {
        try{
            ProcessRule retProcessRule = this.processRuleService.create(data);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_SUCCESS,logModule+retProcessRule.getName());
            return new Result<>(Result.CODE_SUCCESS, "", retProcessRule);
        } catch(Exception e) {
            LogOperator.err(loggerName, "createProcessRule error:" + data, e);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_FAILED,logModule+e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage(), data);
        }
    }

    @ApiOperation(value="修改流程规则", notes="用户手工指定流程规则并修改，" +
            "需要手动输入流程规则名称和描述信息，流程规则名称不能重复。")
    @ApiImplicitParam(name = "data", value = "流程规则对象", required = true, dataType = "ProcessRule")
    //@PreAuthorize("hasAuthority('modifyProcessRule')")
    @RequestMapping(value="/modifyProcessRule", method = RequestMethod.POST)
    public Result<ProcessRule> modifyProcessRule(@RequestBody ProcessRule data) {
        try{
            ProcessRule retProcessRule = this.processRuleService.modify(data);
            writeLog(LogConstant.OPER_MODIFY,Result.CODE_SUCCESS,logModule+data.getName());
            return new Result<>(Result.CODE_SUCCESS, "", retProcessRule);
        } catch(Exception e) {
            LogOperator.err(loggerName, "modifyProcessRule error:" + data, e);
            writeLog(LogConstant.OPER_MODIFY,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage(), data);
        }
    }

    @ApiOperation(value="删除流程规则", notes="在系统中删除指定流程规则")
    @ApiImplicitParam(name = "data", value = "流程规则对象", required = true, dataType = "ProcessRule")
    //@PreAuthorize("hasAuthority('deleteProcessRule')")
    @RequestMapping(value="/deleteProcessRule", method = RequestMethod.DELETE)
    public Result<ProcessRule> deleteProcessRule(@RequestBody ProcessRule data) {
        try{
            this.processRuleService.delete(data);
            writeLog(LogConstant.OPER_DELETE,Result.CODE_SUCCESS, logModule + data.getName());
            return new Result<>(Result.CODE_SUCCESS, "", data);
        } catch(Exception e) {
            LogOperator.err(loggerName, "deleteProcessRule error:" + data, e);
            writeLog(LogConstant.OPER_DELETE,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage(), data);
        }
    }

    @ApiOperation(value="删除流程规则", notes="在系统中删除指定流程规则")
    //@PreAuthorize("hasAuthority('deleteProcessRule')")
    @RequestMapping(value="/deleteProcessRule/{id}", method = RequestMethod.DELETE)
    public Result<ProcessRule> deleteProcessRule(@ApiParam(value = "流程规则ID", required = true) @PathVariable("id") Long id) {
        try{
            String name = processRuleService.findById(id).getName();
            this.processRuleService.delete(id);
            writeLog(LogConstant.OPER_DELETE,Result.CODE_SUCCESS,logModule + name);
            return new Result<>(Result.CODE_SUCCESS, id.toString());
        } catch(Exception e) {
            LogOperator.err(loggerName, "deleteProcessRule error:id=" + id, e);
            writeLog(LogConstant.OPER_DELETE,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage());
        }
    }

    @ApiOperation(value="查询流程规则列表", notes="通过条件查询流程规则信息，返回List方式" +
            "支持模糊查询。")
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value="/queryProcessRule", method = RequestMethod.GET)
    public List<ProcessRule> queryProcessRule(
            @ApiParam(value = "当前页数， 以1开始。") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "当前页的内容长度。") @RequestParam(value = "size", required = false, defaultValue = "20") int size,
            @ApiParam(value = "排序方式：asc为升序，desc为降序。") @RequestParam(value = "order", required = false, defaultValue = "asc") String order,
            @ApiParam(value = "排序字段，与dto中声明的字段名称一致。") @RequestParam(value = "orderBy", required = false, defaultValue = "id") String orderBy,
            @ApiParam(value = "规则名称，模糊搜索") @RequestParam(value = "name", required = false, defaultValue = "") String name,
            @ApiParam(value = "设备类型ID") @RequestParam(value = "deviceTypeId", required = false) Long deviceTypeId,
            @ApiParam(value = "工单类型ID") @RequestParam(value = "workOrderTypeId", required = false) Long workOrderTypeId) {
        return this.processRuleService.findByCondition(page, size, order, orderBy, name, deviceTypeId, workOrderTypeId);
    }

    @ApiOperation(value="查询流程规则", notes="通过ID查询流程规则详细信息")
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value="/queryProcessRule/{id}", method = RequestMethod.GET)
    public Result<ProcessRule> queryProcessRule(@ApiParam(value = "流程规则ID", required = true) @PathVariable("id") Long id) {
        return new Result<>(Result.CODE_SUCCESS, "", this.processRuleService.findById(id));
    }

    @ApiOperation(value="拷贝流程规则",notes="通过ID拷贝流程规则详细信息")
    @RequestMapping(value="/copyProcessRule/{id}",method = RequestMethod.GET)
    public Result<ProcessRule> copyProcessRule(@ApiParam(value = "流程规则ID",required = true)@PathVariable("id") Long id){
        return new Result<>(Result.CODE_SUCCESS, "",this.processRuleService.copy(id));
    }


    @ApiOperation(value="查询流程规则", notes="通过设备类型ID、工单类型ID、项目ID查询流程规则详细信息")
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value="/queryProcessRuleByDeviceTypeOrderTypeProject", method = RequestMethod.GET)
    public Result<ProcessRule> queryProcessRuleByDeviceTypeOrderTypeProject(
            @ApiParam(value = "设备类型ID", required = true) @RequestParam(value = "deviceTypeId") Long deviceTypeId,
            @ApiParam(value = "工单类型ID", required = true) @RequestParam(value = "workOrderTypeId") Long workOrderTypeId,
            @ApiParam(value = "项目ID", required = true) @RequestParam(value = "projectId") Long projectId) {
        return new Result<>(Result.CODE_SUCCESS, "", this.processRuleService.findByProcessRuleByDeviceTypeOrderTypeProject(deviceTypeId, workOrderTypeId, projectId));
    }

    @ApiOperation(value="查询没有创建流程规则的工单类型名集合", notes="通过设备类型ID、多个工单类型ID、项目ID查询没有创建流程规则工单类型名集合")
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value="/queryOrderTypeIdsNotExistProcessRule", method = RequestMethod.GET)
    public Result<List<String>> queryOrderTypeIdsNotExistProcessRule(
            @ApiParam(value = "设备类型ID", required = true) @RequestParam(value = "deviceTypeId") Long deviceTypeId,
            @ApiParam(value = "工单类型IDs，逗号分隔", required = true) @RequestParam(value = "workOrderTypeIds") String workOrderTypeIds,
            @ApiParam(value = "项目ID", required = true) @RequestParam(value = "projectId") Long projectId) {
        return new Result<>(Result.CODE_SUCCESS, "", this.processRuleService.findOrderTypeIdsNotExistProcessRule(deviceTypeId, workOrderTypeIds, projectId));
    }

    @SuppressWarnings("rawtypes")
    @ApiOperation(value="分页查询流程规则", notes="通过条件查询设备类型信息，返回jqGrid分页JSON形式，支持模糊查询。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cond", value = "JqGrid的条件对象，由JqGrid根据js参数自动封装。" +
                    "构造查询条件queryCond Map对象时，有选择条件的的参数key分别为name,deviceTypeId,workOrderTypeId",
                    required = true, dataType = "TableDataQueryCondition")
    })
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value="/queryProcessRuleJqg", method = RequestMethod.GET)
    public TableJsonData queryProcessRuleJqg(TableDataQueryCondition cond) {
        return this.processRuleService.findByConditionJqg(cond);
    }

    /**
     *
     * @param result
     * @param detail
     */
    private  void  writeLog(String op,String result, String detail){
        OperLog operLog =new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setModule(LogConstantEx.MODULE_SYSTEM);
        operLog.setCommand(op);
        operLog.setResult(result);
        operLog.setOperateUser(ServiceUtils.getLoginUser().getUsername());
        operLog.setDetail(detail);
        operLogService.writeLog(operLog);
    }
}
